//
//  FileManagerModule.m
//  XYLib
//
//  Created by Richard on 2019/4/12.
//  Copyright © 2019年 XY. All rights reserved.
//

#import "FileManagerModule.h"
#import <CommonCrypto/CommonDigest.h>
#import <SSZipArchive.h>
#import "MF_Base64Additions.h"

@implementation FileManagerModule
WX_EXPORT_METHOD_SYNC(@selector(fileExistsAtPath:));
WX_EXPORT_METHOD_SYNC(@selector(moveItemAtPath:toPath:));
WX_EXPORT_METHOD_SYNC(@selector(removeItemAtPath:));
WX_EXPORT_METHOD_SYNC(@selector(fileMD5:));
WX_EXPORT_METHOD_SYNC(@selector(docDir));
WX_EXPORT_METHOD_SYNC(@selector(unzipFile:toPath:key:));
WX_EXPORT_METHOD_SYNC(@selector(writeToFile:toPath:encode:));
WX_EXPORT_METHOD_SYNC(@selector(readFile:encode:));


- (NSString*) docDir {
    static NSString *docPath = nil;
    if (!docPath){
        docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    }
    return docPath;
}

//判断某字符串是否为空
- (BOOL) isBlankString:(NSString *)string {
    if (string == nil || string == NULL) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return YES;
    }
    return NO;
}

- (NSString *) directoryAtPath:(NSString *)path {
    if (path) {
        return [path stringByDeletingLastPathComponent];
    } else {
        return nil;
    }
}

- (BOOL)createDirectoryAtPath:(NSString *)path error:(NSError *__autoreleasing *)error {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    return [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:error];
}


- (BOOL)fileExistsAtPath:(NSString *)path{
    if ([self isBlankString:path]) {
        return NO;
    }
    NSFileManager *fileManager = [NSFileManager defaultManager];
    return [fileManager fileExistsAtPath:path];
}

- (BOOL)moveItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath {
    if ([self isBlankString:srcPath] || [self isBlankString:dstPath]) {
        return NO;
    }
    
    if (![self fileExistsAtPath:srcPath]) {
        return NO;
    }
    
    if ([self fileExistsAtPath:dstPath]) {
        [self removeItemAtPath:dstPath];
    }

    if(![self fileExistsAtPath:[self directoryAtPath:dstPath]]){
        [self createDirectoryAtPath:dstPath error:nil];
    }
    
    return [[NSFileManager defaultManager] moveItemAtPath:srcPath toPath:dstPath error:nil];
}

- (BOOL)removeItemAtPath:(NSString *)path{
    if ([self isBlankString:path]) {
        return NO;
    }
    return [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
}

//文件的MD5加密
-(NSString*)fileMD5:(NSString*)path
{
    NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
    if( handle== nil ) return @""; // file didnt exist
    
    CC_MD5_CTX md5;
    
    CC_MD5_Init(&md5);
    
    BOOL done = NO;
    while(!done)
    {
        NSData* fileData = [handle readDataOfLength:256];
        //        CHUNK_SIZE
        CC_MD5_Update(&md5, [fileData bytes], (unsigned int)[fileData length]);
        if( [fileData length] == 0 ) done = YES;
    }
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5_Final(digest, &md5);
    NSString* s = [NSString stringWithFormat: @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                   digest[0], digest[1],
                   digest[2], digest[3],
                   digest[4], digest[5],
                   digest[6], digest[7],
                   digest[8], digest[9],
                   digest[10], digest[11],
                   digest[12], digest[13],
                   digest[14], digest[15]];
    return s;
}

-(BOOL)writeToFile:(NSString*)data toPath:(NSString*)destPath encode:(NSString*)encode{
    if ([[NSFileManager defaultManager] fileExistsAtPath:destPath]) {
        [self removeItemAtPath:destPath];
    }
    [[NSFileManager defaultManager] createDirectoryAtPath:[destPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil];
    if (data) {
        if (encode && [encode isEqualToString:@"base64"]) {
            NSData * base64 = [NSData dataWithBase64String:data];
            if (base64) {
                return [base64 writeToFile:destPath atomically:TRUE];
            }
        } else {
            return [data writeToFile:destPath atomically:TRUE encoding:NSUTF8StringEncoding error:nil];
        }
    }
    return FALSE;
}

-(NSString*)readFile:(NSString*)filePath encode:(NSString*)encode{
    NSString *string = nil;
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        string = [[ NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    }
    return string;
}


-(BOOL)unzipFile:(NSString*)path toPath:(NSString*)destPath key:(NSString*)key{
    BOOL success = false;
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        if (key == nil || key == NULL) {
            NSString *desKey = [[NSBundle mainBundle].infoDictionary objectForKey:@"DESKEY"];
            key = desKey;
        }
        success = [SSZipArchive unzipFileAtPath:path toDestination:destPath overwrite:YES password:key error:nil delegate:nil];
    }
    return success;
}
@end
